package com.topwalk.step01;

import lombok.extern.slf4j.Slf4j;

/**
 * 无锁程序
 *
 * @author tang
 * @since 2023/10/11
 */
@Slf4j
public class Demo5_3WaitAndNotify {

    private static final Object LOCK = new Object();
    
    public static void main(String[] args) throws InterruptedException {
        new Thread(new ThreadA()).start();
        Thread.sleep(0);
        new Thread(new ThreadB()).start();
    }

    static class ThreadA implements Runnable {

        @Override
        public void run() {
            synchronized (LOCK) {
                for (int i = 0; i < 100; i++) {
                    try {
                        log.debug("Thread A {}", i);
                        LOCK.notifyAll();
                        if (i != 99) {
                            LOCK.wait();
                        }
                    } catch (InterruptedException e) {
                        log.error("", e);
                    }
                }
            }
        }

    }

    static class ThreadB implements Runnable {

        @Override
        public void run() {
            synchronized (LOCK) {
                for (int i = 0; i < 100; i++) {
                    try {
                        log.debug("Thread B {}", i);
                        LOCK.notifyAll();
                        if (i != 99) {
                            LOCK.wait();
                        }
                    } catch (InterruptedException e) {
                        log.error("", e);
                    }
                }
            }
        }

    }

}
